import 'package:flutter_billi/http/core/dio_adapter.dart';
import 'package:flutter_billi/http/core/hi_bet_adapter.dart';
import 'package:flutter_billi/http/core/hi_error.dart';
import 'package:flutter_billi/http/core/mock_adapter.dart';
import 'package:flutter_billi/http/request/base_request.dart';

class HiNet {
  HiNet();

  static HiNet _instance;

  static HiNet getInstance() {
    if (_instance == null) {
      _instance = HiNet();
    }
    return _instance;
  }

  Future fire(BaseRequest request) async {
    HiNetResponse response;
    var error;
    try {
      response = await send(request);
    } on HiNetError catch (e) {
      error = e;
      response = e.data;
      printLog(e.message);
    } catch (e) {
      error = e;
      printLog(e);
    }
    if (response == null) {
      // printLog(response)
      printLog(error);
    }
    var result = response.data;
    printLog(result);

    var statusCode = response.statusCode;

    switch (statusCode) {
      case 200:
        return result;
      case 401:
        throw NeedLogin();
        return;
      case 403:
        throw NeedAuth(result.toString(), data: result);
        return;
      default:
        throw HiNetError(statusCode, result.toString(), data: result);
    }
  }

  Future<dynamic> send<T>(BaseRequest request) async {
    printLog("url: ${request.url()}");
    // printLog("method:${request.httpMethod()}");
    // request.addHeader("token", "12345");
    // printLog("header:${request.header}");
    // 使用mock 发送请求
    // HiNetAdapter adapter = MockAdapter();
    // return adapter.send(request);
    // return Future.value({
    //   "statusCode": 200,
    //   "data": {"code": 0, "message": "success"}
    // });
    HiNetAdapter adapter = DioAdapter();
    return adapter.send(request);
  }

  void printLog(log) {
    print("hinet:${log.toString()}");
  }
}
